import re
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import authenticate
from apps.users.models import User

class UsernameMobileModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
    # username 有可能是手机号 也有可能是 用户名
    # 如果 username 满足 手机号的规则,我们就认为它手机号登陆
        try:
            if re.match(r'1[3-9]\d{9}',username):
                user = User.objects.get(mobile = username)
            else:
                user = User.objects.get(username=username)
        except User.DoesNotExist:
            return None

        if user.check_password(password) and self.user_can_authenticate(user):
            return user

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from meiduo_market import settings


def generic_verify_url(user_id):

    # ② 创建itsdangerous实例
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)
    # ③ 组织数据
    data = {'id': user_id}
    # ④ 加密
    token = s.dumps(data).decode()

    verify_url = 'http://www.meiduo.site:8000/email_active/?token=' + token

    return verify_url


def check_verify_token(token):
    # ② 创建itsdangerous实例
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)
    try:
        result = s.loads(token)
    except Exception:
        return None

    return result.get('id')
